<?php
/*
+ --------------------------------------------------- +
|  Ineo Article Manager - Version 2.x
|  Copyright 2006-2007, Dan Cryer and William McGann
+ --------------------------------------------------- +

Ineo Article Manager is free software; you can redistribute it and/or modify
it under the terms of version 3 of the GNU General Public License as published by
the Free Software Foundation.

Ineo Article Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Ineo; see the file License.txt.  If not, write to
the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.

*/

if ( ! defined( 'IN_ACP' ) )
{
	print "<h1>Incorrect access</h1>You cannot access this file directly. If you have recently upgraded, make sure you upgraded 'admin.php'.";
	exit();
}


class ad_ineo
{
	var $ipsclass;
	var $html;
	var $ineo;

	function auto_run()
	{
		// Load version file and set our version:
		require_once( ROOT_PATH . 'sources/ineo/version.php' );
		$this->versiondata = $version;
		
		// Load Ineo core.
		require_once( ROOT_PATH . 'sources/ineo/ineo.php' );
		$this->base_url = $this->ipsclass->base_url;
		$this->root_path = ROOT_PATH . 'sources/ineo/';
		$this->ineo = new ineo( $this );
		
		// IPB is a PITA and doesn't load component-defined caches in the ACP,
		// so we need to load them ourselves:
		$this->load_ineo_caches();
		
		// Load the categories library file, 'cause we need it.
		$this->ineo->load_library( 'categories' );
		
		$this->version = 22;	
		$this->cbox   = 'tableborder';
		$this->ctitle = 'tableheaderalt';
		$this->row1   = 'tablerow1';
		$this->row2   = 'tablerow2';
		$this->thead  = 'tablesubheader';
		$this->tfoot  = 'tablefooter';
		
		//----
		// Kill Globals:
		//----
		
		$tmp_in = array_merge( $_GET, $_POST, $_COOKIE );
		
		foreach ( $tmp_in as $k => $v )
		{
			unset($$k);
		}
		
    // Figure out what we're doing and call it:
       
    $op = ( !empty( $this->ipsclass->input['code'] ) ) ? $this->ipsclass->input['code'] : 'overview';
		$op = preg_replace( '/([^a-zA-Z0-9_]+)/', '',$op );
        
    if( $this->ipsclass->input['code'] == 'settings' )
    {
      $op = 'show_setup';
    }

		$func = 'op_' . $op;
		
		if ( method_exists( $this, $func ) )
		{
			$this->$func();
		}
		
   	$this->ipsclass->admin->output();
	}
	
	function load_ineo_caches()
	{
		$this->ipsclass->DB->simple_construct(array('select'=>'*','from'=>'cache_store','where'=>'cs_key IN ( \'ineo_cats\',\'ineo_permissions\' )'));
		$this->ipsclass->DB->simple_exec();
		
		while( $cache = $this->ipsclass->DB->fetch_row() )
		{
			if( $cache['cs_array'] == '1' )
			{
				$_cache = unserialize( $cache['cs_value'] );
			}
			else
			{
				$_cache = $cache['cs_value'];
			}
			
			$newcache = array($cache['cs_key'] => $_cache);
			$this->ipsclass->cache = array_merge($this->ipsclass->cache,$newcache);
		}
		
	//	die( '<pre>' . print_r($this->ipsclass->cache,true));
	}
	
	/**
	* Quick function for creating an IPB ACP 'box' ( borderwrap, maintitle, content ):
	*/
	function box( $title, $content )
	{
		$this->ipsclass->html .= "
			<div class='{$this->cbox}'>
			
				<div class='{$this->ctitle}'>
					{$title}
				</div>
				
				{$content}
				
			</div>
			<br />
		";
	}
	
	//--------------------------------------------
	// PAGE HANDLER FUNCTIONS BELOW
	//--------------------------------------------
	
	/**
	* Load and show the Ineo settings.
	*/
	function op_show_setup()
	{
		// Set up page title / description:
		$this->ipsclass->admin->page_title = 'Ineo Settings';
		$this->ipsclass->admin->page_detail = 'These settings allow you to control how Ineo works and customize it for your web site.';
		
		// Load, configure and run the IPB settings class:
		require_once( ROOT_PATH  . 'sources/action_admin/settings.php' );
		
		$settings                     =  new ad_settings();
		$settings->ipsclass           =& $this->ipsclass;
		$settings->get_by_key         =  'ineo';
		$settings->return_after_save  =  'section=components&act=ineo&code=settings';
		
		$settings->setting_view();
	}
	
	/**
	* Generate and show an overview of Ineo for the admin, including latest articles, version data, latest actions, etc.
	*/
	function op_overview()
	{
		// Set up page title and description:
		$this->ipsclass->admin->page_title = 'Ineo Overview';
		$this->ipsclass->admin->page_detail = 'An outline of important statistics and information for your Ineo installation.';
		
		// Version check!
		$check_image_location = 'http://www.veriea.com/scripts/versioncheck.php?product=ineo&siteversion='.$this->versiondata['code'];
		$check_html           = "<img src='{$check_image_location}' alt='Version Check' />";
		
		// Load version history:
		$this->ipsclass->DB->simple_construct(
												array( 
														'select' => '*',
														'from' => 'ineo_upgrade_history',
													 )
												);
		$this->ipsclass->DB->simple_order('ineo_upgrade_id DESC');
		$this->ipsclass->DB->simple_exec();
		
		$versions = '';
		
		while( $v = $this->ipsclass->DB->fetch_row() )
		{
			$date = $this->ipsclass->get_date($v['ineo_upgrade_date'],'');
			$versions .= "<tr><td class='{$this->row2}'>{$v['ineo_version_id']} - {$v['ineo_version_human']}</td><td class='{$this->row2}'>{$date}</td></tr>";
		}
		
		// Find out how many articles there are.
		$this->ipsclass->DB->simple_construct( array( 'select' => 'count(*) as cnt', 'from' => 'ineo_articles' ) );
		$this->ipsclass->DB->simple_exec();
		$data = $this->ipsclass->DB->fetch_row();
		$art_count = $data['cnt'];
		
		// Now let's find out how many queued articles there are!
		$this->ipsclass->DB->simple_construct( array( 'select' => 'count(*) as cnt', 'from' => 'ineo_articles', 'where' => 'article_is_queued = 1' ) );
		$this->ipsclass->DB->simple_exec();
		$data = $this->ipsclass->DB->fetch_row();
		$queued_art_count = $data['cnt'];
		
		// Find out how many total revisions there are. $rev_count will only equal non-active revisions, more or less. ;)
		$this->ipsclass->DB->simple_construct( array( 'select' => 'count(*) as cnt', 'from' => 'ineo_content' ) );
		$this->ipsclass->DB->simple_exec();
		$data = $this->ipsclass->DB->fetch_row();
		$rev_count = $data['cnt'] - $art_count;
		
		// Now let's find out how many queued revisions there are!
		$this->ipsclass->DB->simple_construct( array( 'select' => 'count(*) as cnt', 'from' => 'ineo_content', 'where' => 'content_is_queued = 1' ) );
		$this->ipsclass->DB->simple_exec();
		$data = $this->ipsclass->DB->fetch_row();
		$queued_rev_count = $data['cnt'];
		
		$this->ipsclass->html .= <<<OVERVIEW
		
		<div style='text-align: right'>{$check_html}</div>
		<br />
		<table class='ipbtable' style='width: 100%'>
			<tr>
				<td style='vertical-align: top; width: 50%'>
					<div class='{$this->cbox}'>
						<div class='{$this->ctitle}'>
							Statistics
						</div>
						
						<table class='ipbtable' style='width: 100%' cellspacing='0'>
							<tr>
								<td class='{$this->row2}'>
								<strong>Ineo Version</strong>
								</td>
								<td class='{$this->row2}'>
								{$this->versiondata['human']}
								</td>
							</tr>
							<tr>
								<td class='{$this->row2}'>
								<b>Total Articles</b>
								</td>
								<td class='{$this->row2}'>
								{$art_count}
								</td>
							</tr>
							<tr>
								<td class='{$this->row2}'>
								<b>Non-active Revisions</b>
								</td>
								<td class='{$this->row2}'>
								{$rev_count}
								</td>
							</tr>
								<td class='{$this->row2}'>
								<b>Queued Articles</b>
								</td>
								<td class='{$this->row2}'>
								{$queued_art_count}
								</td>
							</tr>
								<td class='{$this->row2}'>
								<b>Queued Revisions</b>
								</td>
								<td class='{$this->row2}'>
								{$queued_rev_count}
								</td>
							</tr>
						</table>
					</div>
				</td>
				<td style='vertical-align: top;'>
					<div class='{$this->cbox}'>
						<div class='{$this->ctitle}'>
							Upgrade History
						</div>
						<table class='ipbtable' style='width: 100%' cellspacing='0'>
							<tr>
								<th class='{$this->thead}'>Version Information</th>
								<th class='{$this->thead}'>Date Installed</th>
							</tr>
							
							{$versions}
						</table>
					</div>
				</td>
			</tr>
		</table>
		
OVERVIEW;
		
		//-----
		// Load and show 5x moderator logs!
		//-----
		$this->ipsclass->DB->simple_construct( array('select' => 'l.*,m.members_display_name','from'=>array('ineo_logs' => 'l'), 'add_join' => array( 1=> array('type' => 'left','from' => array('members'=>'m'), 'where' => 'm.id = l.member_id'))) );
		$this->ipsclass->DB->simple_order('l.id DESC');
		$this->ipsclass->DB->simple_limit('5');
		$this->ipsclass->DB->simple_exec();

		$ROW = '';
		
		// loooooooooooooooooooop!
		while( $res = $this->ipsclass->DB->fetch_row() )
		{
			$date = $this->ipsclass->get_date($res['time'],'');
			$ROW .= "
			<tr>
				<td class='{$this->row1}'>
					{$res['note']}
				</td>
				<td class='{$this->row1}'>
					{$res['members_display_name']}
				</td>
				<td class='{$this->row1}'>
					{$date}
				</td>
			</tr>";
		}
		
		$this->ipsclass->html .= <<<UBERVOO
		<br />
			<div class='{$this->cbox}' style='margin: 2px;'>
				<div class='{$this->ctitle}'>
					Last 5 Moderator Actions
				</div>

				<table class='ipbtable' style='width: 100%' cellspacing='0'>
					<tr>
						<th class='{$this->thead}'>Action</th>
						<th class='{$this->thead}'>Member</th>
						<th class='{$this->thead}'>Date</th>
					</tr>
					{$ROW}
				</table>

			</div>
		<br />
UBERVOO;
		
		
		//-----
		// Load and show latest / recent updated articles:
		//-----
		
		$added = $this->get_recent('article_id');
		$updated = $this->get_recent('article_edited_date');
		
		$this->ipsclass->html .= <<<OVERVIEW

		<table class='ipbtable' style='width: 100%'>
			<tr>
				<td style='vertical-align: top; width: 50%'>
					<div class='{$this->cbox}'>
						<div class='{$this->ctitle}'>
							Latest Added
						</div>

						<table class='ipbtable' style='width: 100%' cellspacing='0'>
							<tr>
								<th class='{$this->thead}'>Title</th>
								<th class='{$this->thead}'>Date</th>
							</tr>
							{$added}
						</table>
					</div>
				</td>
				<td style='vertical-align: top;'>
					<div class='{$this->cbox}'>
						<div class='{$this->ctitle}'>
							Recently Updated
						</div>
						<table class='ipbtable' style='width: 100%' cellspacing='0'>
							<tr>
								<th class='{$this->thead}'>Title</th>
								<th class='{$this->thead}'>Date</th>
							</tr>
							{$updated}
						</table>
					</div>
				</td>
			</tr>
		</table>

OVERVIEW;
		
	}
	
	/**
	* Load recent articles by their update or added date. Used only by the above function.
	*/
	function get_recent( $column_name )
	{
		// Query:
		$this->ipsclass->DB->simple_construct( array(
														'select' => 'article_id,article_title,article_edited_date',
														'from'   => 'ineo_articles',
														'where' => 'article_is_queued = \'0\'',
													)
											);
		$this->ipsclass->DB->simple_order( $column_name . ' DESC' );
		$this->ipsclass->DB->simple_limit( 5 );									
		$list = $this->ipsclass->DB->simple_exec();
		
		$articles = '';
		
		// Build list using the template:
		while( $res = $this->ipsclass->DB->fetch_row( $list ) )
		{
			// Make the date from timestamp:
			$res['article_date'] = $this->ipsclass->get_date($res['article_edited_date'],'');
			
			$articles .= "<tr><td class='{$this->row2}'>{$res['article_title']}</td><td class='{$this->row2}'>{$res['article_date']}</td></tr>";
		}
		
		return $articles;
	}
	
	/**
	* Load and show permissions!
	*/
	function op_permissions()
	{
		$category = 'global';
		$this->ipsclass->admin->page_title = 'Ineo Global Permissions';
		$this->ipsclass->admin->page_detail = 'Here you can control the access rights of each member group.';
		
		if( !empty( $this->ipsclass->input['category']) )
		{
			$category = intval( $this->ipsclass->input['category'] );
			$cat = $this->ipsclass->cache['ineo_cats'][$category]['info'];
			$this->ipsclass->admin->page_title = 'Permissions for Category: ' . $cat['category_name'];
		}
		
		$rows = $this->get_group_perms($category);
		
		// JS crap:
		$this->ipsclass->html .= <<<SCRIPT
	<script type='text/javascript'>
	
	function check_all_group( group_id , new_value )
	{
		var cView    = document.getElementById('view_' + group_id );
		var cAdd     = document.getElementById('add_' + group_id );
		var cEdit    = document.getElementById('edit_' + group_id );
		var cQueue   = document.getElementById('queue_' + group_id );
		var cUpload  = document.getElementById('upload_' + group_id );
		var cIsMod   = document.getElementById('ismod_' + group_id );
		
		cView.checked = new_value;
		cAdd.checked  = new_value;
		cEdit.checked = new_value;
		cQueue.checked = new_value;
		cUpload.checked = new_value;
		cIsMod.checked = new_value;
	}	
	
	function check_all_type( type_id , new_value )
	{
		var frm = document.getElementById('permissions-form');
		var checks = frm.getElementsByTagName('input');
		
		for( var i = 0; i <= checks.length; i++ )
		{
			var box = checks[i];
			var bid = box.id;
			var typ = bid.replace( /^(.+?)_.+?$/, "$1" );
			
			if( typ == type_id )
			{
				box.checked = new_value;
			}
		}
	}
	
	function check_all( new_value )
	{
		var frm = document.getElementById('permissions-form');
		var checks = frm.getElementsByTagName('input');
		
		for( var i = 0; i <= checks.length; i++ )
		{
			var box = checks[i];
			box.checked = new_value;
		}
	}
	
	</script>
SCRIPT;
		
		$html = '<form id="permissions-form" action="'.$this->ipsclass->base_url.'&section=components&act=ineo&code=do_perms" method="post">
	<input type="hidden" name="permission_type" value="'.$category.'" />
		         <table style="border-spacing: 0px" width="100%" cellspacing="0" cellpadding="0" style="margin: 0px">
  					  '.$rows.'
            </table></form>';
		
		$this->box( 'Permissions', $html );
	}
	
	/**
	* Get group permissions
	*/
	function get_group_perms( $category = 'global' )
	{
		// Load the permissions cache:
		$this->perms =& $this->ipsclass->cache['ineo_permissions'][$category];
		
		if( !empty($this->ipsclass->input['msg']) )
		{
			// If we've just updated some permissions, lets make that known!
			$this->box('Permissions Updated','<table style="width: 100%"><td class="{$this->row2}">The permissions cache has been updated!</td></table>');
		}
		
		// Load all of the groups in the groups table:
		$getgroups = array('select' => 'g_id, g_title', 'from' => 'groups');
	  	$this->ipsclass->DB->simple_construct($getgroups);
    	$this->ipsclass->DB->simple_order( 'g_title ASC' );
    	$this->ipsclass->DB->simple_exec();
    	
		if( $category == 'global' )
		{
			$rows .= $this->permissions_row(array('g_id' => 0, 'g_title' => 'Global Default'));
		}
		
		// loop groups, show perms:
    	while ( $perm = $this->ipsclass->DB->fetch_row() )
    	{
      		$rows .= $this->permissions_row($perm);
    	}
    
		$rows .= <<<CHECKVERT
<tr>
	<td colspan='7' class='{$this->thead}'>
		Toggle All Groups
	</td>
</tr>

	<tr>
		<td class='{$this->row1}' style='text-align: center;'>
			<input style='width: 20px; height: 20px; background: #f5cdcd; border: 1px solid #777777; font-weight: bold;' type="button" id="button" value="+" onclick="javascript:check_all('checked')" />&nbsp;
			<input style='width: 20px; height: 20px; background: #f5cdcd; border: 1px solid #777777; font-weight: bold;' type="button" id="button" value="-" onclick="javascript:check_all('')" />
		</td>
		<td class="{$this->row1}" valign="middle" style="text-align: center; padding: 5px">
			<input style='width: 20px; height: 20px;' type="button" id="button" value="+" onclick="javascript:check_all_type('view','checked')" />&nbsp;
			<input style='width: 20px; height: 20px;' type="button" id="button" value="-" onclick="javascript:check_all_type('view','')" />
		</td>
		<td class="{$this->row1}" valign="middle" style="text-align: center; padding: 5px">
			<input style='width: 20px; height: 20px;' type="button" id="button" value="+" onclick="javascript:check_all_type('add','checked')" />&nbsp;
			<input style='width: 20px; height: 20px;' type="button" id="button" value="-" onclick="javascript:check_all_type('add','')" />
		</td>
		<td class="{$this->row1}" valign="middle" style="text-align: center; padding: 5px">
			<input style='width: 20px; height: 20px;' type="button" id="button" value="+" onclick="javascript:check_all_type('edit','checked')" />&nbsp;
			<input style='width: 20px; height: 20px;' type="button" id="button" value="-" onclick="javascript:check_all_type('edit','')" />
		</td>
		<td class="{$this->row1}" valign="middle" style="text-align: center; padding: 5px">
			<input style='width: 20px; height: 20px;' type="button" id="button" value="+" onclick="javascript:check_all_type('queue','checked')" />&nbsp;
			<input style='width: 20px; height: 20px;' type="button" id="button" value="-" onclick="javascript:check_all_type('queue','')" />
		</td>
		<td class="{$this->row1}" valign="middle" style="text-align: center; padding: 5px">
			<input style='width: 20px; height: 20px;' type="button" id="button" value="+" onclick="javascript:check_all_type('upload','checked')" />&nbsp;
			<input style='width: 20px; height: 20px;' type="button" id="button" value="-" onclick="javascript:check_all_type('upload','')" />
		</td>
		<td class="{$this->row1}" valign="middle" style="text-align: center; padding: 5px">
			<input style='width: 20px; height: 20px;' type="button" id="button" value="+" onclick="javascript:check_all_type('ismod','checked')" />&nbsp;
			<input style='width: 20px; height: 20px;' type="button" id="button" value="-" onclick="javascript:check_all_type('ismod','')" />
		</td>
	</tr>
CHECKVERT;

    	$rows .= '<tr><td class="'.$this->tfoot.'" colspan="8" align="center"><input value="Update Group Permissions" id="button" accesskey="s" type="submit"></td></tr>';
    
    	return $rows;
	}
	
	function permissions_row( $perm )
	{
		$gid    = $perm['g_id'];
  		$title  = $perm['g_title'];
  		$view   = ( $this->perms[$gid]['view']   != '1' ) ? '' : 'checked="checked" ';
  		$add    = ( $this->perms[$gid]['add']    != '1' ) ? '' : 'checked="checked" ';
 		$edit   = ( $this->perms[$gid]['edit']   != '1' ) ? '' : 'checked="checked" ';
  		$queue  = ( $this->perms[$gid]['avoid_queue']  != '1' ) ? '' : 'checked="checked" ';
  		$upload = ( $this->perms[$gid]['upload'] != '1' ) ? '' : 'checked="checked" ';
  		$ismod  = ( $this->perms[$gid]['moderate']  != '1' ) ? '' : 'checked="checked" ';
		
  		return '
		<tr>
			<td colspan="7" class='.$this->thead.'>
				'.$title.'
			</td>
		</tr>
<tr>
			<td class="'.$this->row1.'" valign="middle" style="padding: 0; text-align: center;">
				<input style="width: 20px; height: 20px" type="button" id="button" value="+" onclick="javascript:check_all_group('.$gid.',\'checked\')" />&nbsp;
				<input style="width: 20px; height: 20px" type="button" id="button" value="-" onclick="javascript:check_all_group('.$gid.',\'\')" />
			</td>
			
            <td valign="middle" style="background-color:#dbe6ea;" class="'.$this->row2.'">
				<div id="mgyellow" class="yellow-perm" style="text-align: center; padding: 5px;">
					View <input id="view_'.$gid.'" name="view_'.$gid.'" value="1" '.$view.'type="checkbox">
				</div>
			</td>
			<td valign="middle" style="background-color:#d2d5f2" class="'.$this->row2.'">
				<div id="mgblue" class="blue-perm" style="text-align: center; padding: 5px">
					Add <input id="add_'.$gid.'" name="add_'.$gid.'" value="1" '.$add.'type="checkbox">
				</div>
			</td>
			<td valign="middle" style="background-color:#dbe2de" class="'.$this->row2.'">
				<div id="mggreen" class="green-perm" style="text-align: center; padding: 5px">
					Edit <input id="edit_'.$gid.'" name="edit_'.$gid.'" value="1" '.$edit.'type="checkbox">
				</div>
			</td>
			<td valign="middle" style="background-color:#ecd5d8" class="'.$this->row2.'">
				<div id="mgred" class="red-perm" style="text-align: center; padding: 5px;">
					Avoid Queue <input id="queue_'.$gid.'" name="queue_'.$gid.'" value="1" '.$queue.'type="checkbox">
				</div>
			</td>
			<td valign="middle" style="background-color:#ece6d8" class="'.$this->row2.'">
				<div id="memgroup" class="orange-perm" style="text-align: center; padding: 5px">
					Upload <input id="upload_'.$gid.'" name="upload_'.$gid.'" value="1" '.$upload.'type="checkbox">
				</div>
			</td>
			<td valign="middle" style="background-color:#dfdee9" class="'.$this->row2.'">
				<div id="mgyellow" class="purple-perm" style="text-align: center; padding: 5px;">
					Moderate <input id="ismod_'.$gid.'" name="ismod_'.$gid.'" value="1" '.$ismod.'type="checkbox">
				</div>
			</td>';
	}
	
	/**
	* Get incoming permissions, update the database with new values:
	*/
	function op_do_perms()
	{
		// Load groups first:
		$this->ipsclass->DB->simple_construct( array( 'select' => 'g_id', 'from' => 'groups' ) );
		$this->ipsclass->DB->simple_order( 'g_id ASC' );
		$loop = $this->ipsclass->DB->simple_exec();
	  
		$category = $this->ipsclass->input['permission_type'];
		
		if( !empty( $this->ipsclass->input['view_0'] ) )
		{
			// Set global default if we're doing global perms:
			$this->set_permissions( $category, 0 );
		}
		
		// loop through all of the groups, if permissions are set for it, update the db. If not, don't. Simple as.
	  	while ( $group = $this->ipsclass->DB->fetch_row($loop) )
	  	{
	    	$this->set_permissions( $category, $group['g_id'] );
	  	}
	  	
		if( $category == 'global' )
		{
			$actions = '&section=components&act=ineo&code=permissions&msg=1';
			$this->ipsclass->boink_it($this->ipsclass->base_url.$actions);
		}
		else
		{
			$actions = '&section=components&act=ineo&code=permissions&category='.$category.'&msg=1';
			$this->ipsclass->boink_it($this->ipsclass->base_url.$actions);
		}	
	}
	
	function set_permissions( $category, $group )
	{
		$view   = ( isset($this->ipsclass->input['view_' . $group]  ) ) ? '1' : '-1';
    	$add    = ( isset($this->ipsclass->input['add_' . $group]   ) ) ? '1' : '-1';
    	$edit   = ( isset($this->ipsclass->input['edit_' . $group]  ) ) ? '1' : '-1';
    	$queue  = ( isset($this->ipsclass->input['queue_' . $group] ) ) ? '1' : '-1';
    	$upload = ( isset($this->ipsclass->input['upload_' . $group]) ) ? '1' : '-1';
    	$ismod  = ( isset($this->ipsclass->input['ismod_' . $group] ) ) ? '1' : '-1';
    
		$permissions = array( 'view' => $view , 'add' => $add , 'edit' => $edit, 'avoid_queue' => $queue, 'upload' => $upload, 'moderate' => $ismod );
						
		$this->ipsclass->cache['ineo_permissions'][$category][$group] = $permissions;
		
		$this->ipsclass->update_cache( array( 'name' => 'ineo_permissions', 'array' => 1, 'deletefirst' => 1 ) );
	}
	
	/**
	* Load and show moderator logs
	*/
	function op_logs()
	{
		$this->ipsclass->admin->page_title = 'Ineo Moderator Logs';
		$this->ipsclass->admin->page_detail = 'This page allows you to view the latest moderator actions in Ineo.';
		
	  // Count the number of friggin' logs, yarr.
	  $this->ipsclass->DB->simple_select( 'count(*) as cnt', 'ineo_logs' );
	  $this->ipsclass->DB->simple_exec();
	  $count = $this->ipsclass->DB->fetch_row();
	
		$_START = intval( $this->ipsclass->input['st'] );
	  
		$links = $this->ipsclass->build_pagelinks( array( 'TOTAL_POSS' => $count['cnt'],
		                                                  'PER_PAGE' => 20,
		                                                  'CUR_ST_VAL' => $_START,
		                                                  'BASE_URL'    => $this->ipsclass->base_url.'&section=components&act=ineo&code=logs',) );
		
		$rows = $this->get_logs($_START);
		
		$this->box( 'Moderator Logs', $rows );
		$this->ipsclass->html .= $links;
	}
	
	/**
	* Get moderator logs from the db, pass an offset and suchlike:
	*/
	function get_logs( $offset )
	{
	  $this->ipsclass->DB->simple_construct( 
												array(
													
													'select' => 'l.*,m.members_display_name', 
													'from' => array('ineo_logs'=>'l'),
													'add_join' => array(
																		
																		1 => array(
																					
																					'type' => 'left',
																					'from' => array('members'=>'m'),
																					'where' => 'm.id = l.member_id',
																				
																					)
																		
																		)
													) 
											);
	  $offset = ( $offset == '' ) ? 0 : $offset;
	  $this->ipsclass->DB->simple_order('id DESC');
	  $this->ipsclass->DB->simple_limit($offset, 20);
	  $this->ipsclass->DB->simple_exec();
	  
	  $rows = '<table style="border-spacing: 0px" width="100%" cellspacing="0" cellpadding="5" style="margin: 0px">
	           <tr>
               <td class="' . $this->thead . '" align="center">Act</td>
               <td class="' . $this->thead . '" align="center">Code</td>
               <td class="' . $this->thead . '" align="center">Note</td>
               <td class="' . $this->thead . '" align="center">Member</td>
               <td class="' . $this->thead . '" align="center">Time</td>
               <td class="' . $this->thead . '" align="center">IP Address</td>
             </tr>';
	  
    while ( $log = $this->ipsclass->DB->fetch_row() )
    {
      $rows .= '<tr>
                  <td class="'.$this->row1.'" valign="middle">'.$log['act'].'</td>
                  <td class="'.$this->row2.'" valign="middle">'.$log['code'].'</td>
                  <td class="'.$this->row1.'" valign="middle">'.$log['note'].'</td>
                  <td class="'.$this->row2.'" valign="middle">'.$log['members_display_name'].'</td>
                  <td class="'.$this->row1.'" valign="middle">'.$this->ipsclass->get_date($log['time'],'').'</b></td>
                  <td class="'.$this->row1.'" valign="middle">'.$log['ip_address'].'</td>
                </tr>';
    }
    
		$rows .= '</table>';
		
    return $rows;
	}
	
	/**
	* Load and show categories!
	*/
	function op_categories()
	{
		$this->ipsclass->admin->page_title = 'Category Manager';
		$this->ipsclass->admin->page_detail = 'From here you can manage your existing categories and add new ones.';
		
		$this->ipsclass->input['id'] = empty($this->ipsclass->input['id']) ? 0 : intval($this->ipsclass->input['id']);
		$cat_list = $this->get_cat_list($this->ipsclass->input['id']);
		
		$this->box( 'Categories' , "
				<table style='border-spacing: 1px' width='100%' cellspacing='0' cellpadding='0' style='margin: 0px'>
				<form action='{$this->ipsclass->base_url}&section=components&act=ineo&code=cat_order' method='POST'>
				<input type='hidden' name='id' value='{$this->ipsclass->input['id']}'>
					<tr>
						<td class='".$this->thead."' style='margin: 0; border: 0;'>Category</td>
						<td class='".$this->thead."' style='width: 10px; margin: 0; border: 0;'>Order</td>
						<td class='".$this->thead."' style='width: 10px; margin: 0; border: 0;'>Options</td>
					</tr>
					{$cat_list}
					<tr>
						<td colspan='3' class='".$this->tfoot."' style='text-align: right;'>
							<input type='submit' class='realbutton' value='Reorder Categories'></form> <form action='{$this->ipsclass->base_url}&section=components&act=ineo&code=new_cat&parent={$this->ipsclass->input['id']}' method='POST'><input type='submit' class='realbutton' value='New Category'></form>
						</td>
					</tr>
				</table>
			" );
	}
	
	/**
	* Reorder categories:
	*/
	function op_cat_order()
	{
	  foreach ( $_POST as $key => $value )
	  {
		$value = intval( $value );
		
	    if ( $key != 'id' )
	    {
	      $this->ipsclass->DB->do_update( 'ineo_categories', array( 'category_order' => $value ), 'category_id = \''.intval(str_replace('order_dropdown_', '', $key)).'\'') ;
	    }
	  }
	  
	  $return = '<div class="tablefooter"><strong>Category order updated.</strong></div>';
	  
	  $this->box('Success!', $return);
	  
	  $this->ineo->libs['categories']->rebuild_cat_cache();
	  
	  $this->op_categories();
	}
	
	/**
	* Get a list of categories from the database:
	*/
	function get_cat_list($id)
	{
		$this->ipsclass->DB->simple_construct( array(
											'select' => 'c.*, count( cnt.category_id ) as subcat_count',
											'from'   => array( 'ineo_categories' => 'c' ),
											'add_join' => array( 1 => array(
											                     'type' => 'left',
											                     'from' => array( 'ineo_categories' => 'cnt' ),
											                     'where' => 'cnt.category_parent = c.category_id' )),
											'where' => 'c.category_parent = ' . $id . ' group by c.category_id' ));
		$this->ipsclass->DB->simple_order( 'category_order, category_name ASC' );
		$queery = $this->ipsclass->DB->simple_exec();
		
		$catcount = $this->ipsclass->DB->get_num_rows();
		
		$list = '';
		
		while( $cat = $this->ipsclass->DB->fetch_row($queery) )
		{
		  $children = $cat['subcat_count'];
		  
			$cat_dropdown = $this->order_dropdown( $cat['category_id'], $cat['category_order'], $catcount );
			
			$sublink = "<a href='{$this->ipsclass->base_url}&section=components&act=ineo&code=categories&id={$cat['category_id']}'>";
			$children = ( $children > 0 ) ? "( <strong>{$sublink}{$children}</a></strong> children )" : "";
			
			$list .= "
					<tr>
						<td class='".$this->row2."' style='padding: 5px'><strong>{$sublink}{$cat['category_name']}</a></strong> {$children}<br />{$cat['category_desc']}</td>
						
						<td class='".$this->row2."' style='padding: 5px'>{$cat_dropdown}</td>
						
						<td class='".$this->row1."' style='padding: 5px; text-align: center; '>
						
						<img src='skin_acp/IPB2_Standard/images/filebrowser_action.gif' class='ipd' alt='Options' id='cat-options-{$cat['category_id']}' />
						
						<script type='text/javascript'>
						menu_build_menu(
							'cat-options-{$cat['category_id']}',
							new Array(
									img_item + \"&nbsp; <a href='{$this->ipsclass->base_url}&section=components&act=ineo&code=edit_cat&cat_id={$cat['category_id']}'>Edit Category</a>\",
									img_item + \"&nbsp; <a href='{$this->ipsclass->base_url}&section=components&act=ineo&code=permissions&category={$cat['category_id']}'>Edit Permissions</a>\",
									img_item + \"&nbsp; <a href='{$this->ipsclass->base_url}&section=components&act=ineo&code=delete_cat&cat_id={$cat['category_id']}'>Delete Category</a>\",
									img_item + \"&nbsp; <a href='{$this->ipsclass->base_url}&section=components&act=ineo&code=empty_cat&cat_id={$cat['category_id']}'>Empty Category</a>\",
									img_item + \"&nbsp; {$sublink}View Children</a>\"
								)
							);
						 </script>
						
						</td>
					</tr>
					";
		}
		
		
		return $list;
	}
	
	/**
	* Make a dropdown select for reordering, giving only as many numbers as categories.
	*/
	function order_dropdown( $catid, $current_order, $total )
	{
	  $return = '<select name="order_dropdown_'.$catid.'">';
	  for ( $i=1; $i <= $total; $i++ )
	  {
	    $selected = ( $i == $current_order ) ? 'selected' : '' ;
	    $return .= '<option value="'.$i.'" '.$selected.'>'.$i.'</option>';
	  }
	  $return .= '</select>';
	  
	  return $return;
	}
	
	/**
	* Delete a category:
	*/
	function op_delete_cat()
	{
		$this->ipsclass->admin->page_title = 'Delete Category';
		$this->ipsclass->admin->page_detail = 'You can remove a category from here. Please note that the category must be empty and there must be no subcategories in this category.';
	  
		$this->ipsclass->DB->simple_construct( array( 'select' => 'count(*) as count', 'from' => 'ineo_articles', 'where' => 'article_cat_id = '.intval($this->ipsclass->input['cat_id']) ) );
		$this->ipsclass->DB->simple_exec();
		$data = $this->ipsclass->DB->fetch_row();
		
		if ( $data['count'] != 0 )
		{
		  $opts .= '<table width="100%"><tr><td class="tablerow1" style="padding: 5px;" colspan="2"><strong>Category is not empty!</strong><br /><i>You cannot delete a category that is not empty. Use the form below to move/delete articles in this category.</i></td></tr>';
	    $opts .= '<tr><td class="tablerow1" style="padding: 5px;"><strong>Move Articles?</strong><br /><i>Choose the category to send all articles from this category to.</i></td>';
	    $opts .= '<td class="tablerow2" style="padding: 5px;"><form action="'.$this->ipsclass->base_url.'&section=components&act=ineo&code=do_empty_cat_move&cat_id='.intval($this->ipsclass->input['cat_id']).'" method="POST">'.$this->build_dropdown( null, true ).' <input type="submit" class="realbutton" value="Move Articles"></form></td></tr>';
	    $opts .= '<tr><td class="tablerow1" style="padding: 5px;"><strong>Empty Category</strong><br /><i>All articles in the category will be deleted.</i></td>';
	    $opts .= '<td class="tablerow2" style="padding: 5px;"><form action="'.$this->ipsclass->base_url.'&section=components&act=ineo&code=do_empty_cat&cat_id='.intval($this->ipsclass->input['cat_id']).'" method="POST"><input type="submit" class="realbutton" value="Delete Articles"></form></td></tr></table>';
		  
	    $this->box( 'Warning!', $opts );
		  
	    return true;
		}
		
		$this->ipsclass->DB->simple_construct( array( 'select' => 'count(*) as count', 'from' => 'ineo_categories', 'where' => 'category_parent = '.intval($this->ipsclass->input['cat_id']) ) );
	  $this->ipsclass->DB->simple_exec();
		$data = $this->ipsclass->DB->fetch_row();
		
		if ( $data['count'] != 0 )
		{
		  $opts .= '<table width="100%"><tr><td class="tablerow1" style="padding: 5px;" colspan="2"><strong>Category has subcategories!</strong><br /><i>You cannot delete a category that is not empty. Use the form below to move this category\'s subcats into another category.</i></td></tr>';
	    $opts .= '<tr><td class="tablerow1" style="padding: 5px;"><strong>Move Subcats?</strong><br /><i>Choose the category to send all subcats from this category to.</i></td>';
	    $opts .= '<td class="tablerow2" style="padding: 5px;"><form action="'.$this->ipsclass->base_url.'&section=components&act=ineo&code=move_subcats&cat_id='.intval($this->ipsclass->input['cat_id']).'" method="POST">'.$this->build_dropdown().' <input type="submit" class="realbutton" value="Move Subcategories"></form></td></tr></table>';
	    $this->box( 'Warning!', $opts );
		  
	    return true;
		}
		
	  $do_it = '<table width="100%"><tr><td class="tablerow1" style="padding: 5px;"><strong>Are you sure?</strong><br /><i>There is <b>NO</b> way to undo this action.</i></td><td class="tablerow2" style="padding: 5px;"><form action="'.$this->ipsclass->base_url.'&section=components&act=ineo&code=do_delete_cat&cat_id='.intval($this->ipsclass->input['cat_id']).'" method="POST"><input type="submit" class="realbutton" value="Delete Category"></form></td></tr></table>';
	  $this->box( 'Confirmation', $do_it );
	}
	
	function op_do_delete_cat()
	{
		$this->ipsclass->DB->simple_construct( array( 'select' => 'count(*) as count', 'from' => 'ineo_articles', 'where' => 'article_cat_id = '.intval($this->ipsclass->input['cat_id']) ) );
		$this->ipsclass->DB->simple_exec();
		$data = $this->ipsclass->DB->fetch_row();
		
		if ( $data['count'] != 0 )
		{
		  $opts .= '<table width="100%"><tr><td class="tablerow1" style="padding: 5px;" colspan="2"><strong>Category is not empty!</strong><br /><i>You cannot delete a category that is not empty. Use the form below to move/delete articles in this category.</i></td></tr>';
	    $opts .= '<tr><td class="tablerow1" style="padding: 5px;"><strong>Move Articles?</strong><br /><i>Choose the category to send all articles from this category to.</i></td>';
	    $opts .= '<td class="tablerow2" style="padding: 5px;"><form action="'.$this->ipsclass->base_url.'&section=components&act=ineo&code=do_empty_cat_move&cat_id='.intval($this->ipsclass->input['cat_id']).'" method="POST">'.$this->build_dropdown( null, true ).' <input type="submit" class="realbutton" value="Move Articles"></form></td></tr>';
	    $opts .= '<tr><td class="tablerow1" style="padding: 5px;"><strong>Empty Category</strong><br /><i>All articles in the category will be deleted.</i></td>';
	    $opts .= '<td class="tablerow2" style="padding: 5px;"><form action="'.$this->ipsclass->base_url.'&section=components&act=ineo&code=do_empty_cat&cat_id='.intval($this->ipsclass->input['cat_id']).'" method="POST"><input type="submit" class="realbutton" value="Delete Articles"></form></td></tr></table>';
		  
	    $this->box( 'Warning!', $opts );
		  
	    return true;
		}
		
		$this->ipsclass->DB->simple_construct( array( 'select' => 'count(*) as count', 'from' => 'ineo_categories', 'where' => 'category_parent = '.intval($this->ipsclass->input['cat_id']) ) );
	  $this->ipsclass->DB->simple_exec();
		$data = $this->ipsclass->DB->fetch_row();
		
		if ( $data['count'] != 0 )
		{
		  $opts .= '<table width="100%"><tr><td class="tablerow1" style="padding: 5px;" colspan="2"><strong>Category has subcategories!</strong><br /><i>You cannot delete a category that is not empty. Use the form below to move this category\'s subcats into another category.</i></td></tr>';
	    $opts .= '<tr><td class="tablerow1" style="padding: 5px;"><strong>Move Subcats?</strong><br /><i>Choose the category to send all subcats from this category to.</i></td>';
	    $opts .= '<td class="tablerow2" style="padding: 5px;"><form action="'.$this->ipsclass->base_url.'&section=components&act=ineo&code=move_subcats&cat_id='.intval($this->ipsclass->input['cat_id']).'" method="POST">'.$this->build_dropdown().' <input type="submit" class="realbutton" value="Move Subcategories"></form></td></tr></table>';
	    $this->box( 'Warning!', $opts );
		  
	    return true;
		}
		
		$this->ipsclass->DB->simple_delete( 'ineo_categories' , 'category_id = \'' . intval($this->ipsclass->input['cat_id']) . '\'' );
		$this->ipsclass->DB->simple_exec();
		
		$this->ineo->libs['categories']->rebuild_cat_cache();
		
		$this->ipsclass->boink_it( $this->ipsclass->base_url . '&section=components&act=ineo&code=categories' );
	}
	
	function op_move_subcats()
	{
	  if ( $this->ipsclass->input['cat_id'] == $this->ipsclass->input['category_parent'] )
	  {
	    $return .= '<table width="100%"><tr><td class="tablerow1" style="padding: 5px;" colspan="2"><strong>You cannot move subcats back into the same category.</strong><br /><i>That doesn\'t really accomplish much. ;) Use the form below to choose a different destination.</i></td></tr>';
	    $return .= '<tr><td class="tablerow1" style="padding: 5px;"><strong>Move subcats?</strong></td>';
	    $return .= '<td class="tablerow2" style="padding: 5px;"><form action="'.$this->ipsclass->base_url.'&section=components&act=ineo&code=move_subcats&cat_id='.intval($this->ipsclass->input['cat_id']).'" method="POST">'.$this->build_dropdown().' <input type="submit" class="realbutton" value="Move Subcategories"></form></td></tr></table>';
	    $this->box( 'Warning!', $return );
	    return true;
	  }
	  
	  $this->ipsclass->DB->do_update( 'ineo_categories', array( 'category_parent' => $this->ipsclass->input['category_parent'] ), 'category_parent = '.intval($this->ipsclass->input['cat_id']) );
	  
	  $this->ineo->libs['categories']->rebuild_cat_cache();
	  
	  $this->ipsclass->boink_it( $this->ipsclass->base_url . '&section=components&act=ineo&code=categories' );
	}
	
	function op_empty_cat()
	{
		$this->ipsclass->admin->page_title = 'Empty Category';
		$this->ipsclass->admin->page_detail = 'You can either move articles into another category en-masse, or you can delete all articles (and the article\'s revisions, attachments, and watchlists) from here.';
		
		$this->ipsclass->DB->simple_construct( array( 'select' => '*', 'from' => 'ineo_categories', 'where' => 'category_id = '.intval($this->ipsclass->input['cat_id']) ) );
		$this->ipsclass->DB->simple_exec();
		$data = $this->ipsclass->DB->fetch_row();
	  
		$this->ipsclass->admin->page_title = 'Empty Category: '.$data['category_name'];
		$this->ipsclass->admin->page_detail = 'You can move all articles from the <b>'.$data['category_name'].'</b> category into another category, or delete all articles from <b>'.$data['category_name'].'</b> here.';
	  
	 	$opts .= '<table width="100%"><tr><td class="tablerow1" style="padding: 5px;"><strong>Move Articles?</strong><br /><i>Choose the category to send all articles from this category to.</i></td>';
		$opts .= '<td class="tablerow2" style="padding: 5px;"><form action="'.$this->ipsclass->base_url.'&section=components&act=ineo&code=do_empty_cat_move&cat_id='.$this->ipsclass->input['cat_id'].'" method="POST">'.$this->build_dropdown( null, true ).' <input type="submit" class="realbutton" value="Move Articles"></form></td></tr>';
		$opts .= '<tr><td class="tablerow1" style="padding: 5px;"><strong>Empty Category</strong><br /><i>All articles in the category will be deleted.</i></td>';
		$opts .= '<td class="tablerow2" style="padding: 5px;"><form action="'.$this->ipsclass->base_url.'&section=components&act=ineo&code=do_empty_cat&cat_id='.$this->ipsclass->input['cat_id'].'" method="POST"><input type="submit" class="realbutton" value="Delete Articles"></form></td></tr></table>';
	  
		$this->box( 'Empty Category: '.$data['category_name'], $opts );
	}
	
	function op_do_empty_cat_move()
	{
	  $this->ipsclass->DB->do_update( 'ineo_articles', array( 'article_cat_id' => intval($this->ipsclass->input['category_parent']) ), 'article_cat_id = '.intval($this->ipsclass->input['cat_id']) );
	  
	  $this->ineo->libs['categories']->rebuild_cat_cache();
	  
	  $this->ipsclass->boink_it( $this->ipsclass->base_url . '&section=components&act=ineo&code=categories' );
	}
	
	function op_do_empty_cat()
	{
		$this->ipsclass->admin->page_title = 'Emptying Category';
		$this->ipsclass->admin->page_detail = 'This page displays the progress of emptying a category.';
		
	  // Start output buffering, 'cause it rules.
	  ob_start();
	  
	  $this->ipsclass->DB->simple_construct( array( 'select' => 'article_id', 'from' => 'ineo_articles', 'where' => 'article_cat_id = '.intval($this->ipsclass->input['cat_id']) ) );
		$this->ipsclass->DB->simple_limit( '50' );
		$this->ipsclass->DB->simple_exec();
		
		while ( $row = $this->ipsclass->DB->fetch_row() )
		{
		  if ( isset($first) )
		  {
		    $id_string .= ','.$row['article_id'];
		  }
		  else 
		  {
		    $id_string .= $row['article_id'];
		    $first = true;
		  }
		}
		
		$count = $this->ipsclass->DB->get_num_rows();
		
		if ( $count != 0 )
		{
		  // Delete Article, Article Content, Watchlist Items and Ratings.
		  $this->ipsclass->DB->simple_delete( 'ineo_articles'    , 'article_id IN ( ' . $id_string . ' )' );
		  $this->ipsclass->DB->simple_exec();
		  $this->ipsclass->DB->simple_delete( 'ineo_content'     , 'content_article IN ( ' . $id_string . ' )' );
		  $this->ipsclass->DB->simple_exec();
		  $this->ipsclass->DB->simple_delete( 'ineo_watchlists'  , 'watch_id IN ( ' . $id_string . ' ) AND watch_type = 1' );
		  $this->ipsclass->DB->simple_exec();
		  $this->ipsclass->DB->simple_delete( 'ineo_rating'      , 'rate_artid IN ( ' . $id_string . ' )' );
		  $this->ipsclass->DB->simple_exec();
		
		  // Delete article's attachments.
      $this->ipsclass->DB->simple_construct( array( 	'select' => '*',
	                                                 		'from' => 'ineo_attachments',
	                                                		'where' => 'attach_article IN ( ' . $id_string . ' )' ) );
      $this->ipsclass->DB->simple_exec();

      while( $data = $this->ipsclass->DB->fetch_row() )
      {
		    @unlink($data['attach_location']);
      }
    
      // Remove attachment entries in the DB for article.
      $this->ipsclass->DB->simple_delete( 'ineo_attachments', 'attach_article IN ( ' . $id_string . ' )' );
      $this->ipsclass->DB->simple_exec();
		}
		
    // Give 'em a number to see.
    $delcount = $this->ipsclass->input['del_count'];
    $delcount = ( empty($delcount) ) ? $count : $delcount + $count ;
    
    $return = '<table width="100%"><tr><td class="tablerow1" style="padding: 5px;"><strong>Articles deleted</strong></td><td class="tablerow2" style="padding: 5px;">'.$delcount.'</td></tr></table>';
    
    $this->box( 'Deletion progress', $return );
    
    if ( $count != '0' )
    {
      @header( "Refresh: 2;url=".$this->ipsclass->base_url."&section=components&act=ineo&code=do_empty_cat&cat_id=".intval($this->ipsclass->input['cat_id'])."&del_count=".$delcount );
    }
    else
    {
    	$this->ineo->libs['categories']->rebuild_cat_cache();
    	@header( "Refresh: 2;url=".$this->ipsclass->base_url."&section=components&act=ineo&code=categories" );
    }
    
    ob_flush();
	}
	
	function op_edit_cat()
	{
		$this->ipsclass->admin->page_title = 'Edit Category';
		$this->ipsclass->admin->page_detail = 'Edit settings for a category.';
		
		$this->ipsclass->DB->simple_construct( array(
											'select' => '*',
											'from'   => 'ineo_categories',
											'where'  => 'category_id = \'' . intval($this->ipsclass->input['cat_id']) . '\'',
											 ));
		$this->ipsclass->DB->simple_exec();
		
		$cat = $this->ipsclass->DB->fetch_row();
		
		$parent_menu = $this->build_dropdown($cat['category_parent']);
		
		$this->box( 'Edit Category: ' . $cat['category_name'] , 
		"<form action='{$this->ipsclass->base_url}&section=components&act=ineo&code=do_cat_edit&cat_id={$this->ipsclass->input['cat_id']}' method='post'>
		
		<table style='width: 100%' cellspacing='0'>
			<tr>
				<td class='".$this->row1."' style='padding: 5px'><b>Category Name</b><br />The title of the category.</td>
				<td class='".$this->row2."' style='padding: 5px'><input class='forminput' type='text' name='category_name' value='{$cat['category_name']}' /></td>
			</tr>
			<tr>
				<td class='".$this->row1."' style='padding: 5px'><b>Category Description</b><br />A brief description of the category.</td>
				<td class='".$this->row2."' style='padding: 5px'><input class='forminput' type='text' name='category_desc' value='{$cat['category_desc']}' /></td>
			</tr>
			<tr>
			  <td class='".$this->row1."' style='padding: 5px'><b>Parent Category</b><br />Select an existing category to make this a subcategory.</td>
			  <td class='".$this->row2."' style='padding: 5px'>{$parent_menu}</td>
			<tr>
			<tr>
				<td colspan='2' class='".$this->tfoot."' style='text-align: center;'><input type='submit' value='Submit' class='realdarkbutton' /></td>
			</tr>
		</table>
		
		</form>
		" );
	}
	
	function op_new_cat()
	{
	  $this->ipsclass->admin->page_title = 'New Category';
	  $this->ipsclass->admin->page_detail = 'Create a new category.';
	  
	  $parent_menu = $this->build_dropdown(intval($this->ipsclass->input['parent']));
	  
	  $this->box( 'New Category' ,
	  "<form action='{$this->ipsclass->base_url}&section=components&act=ineo&code=do_new_cat' method='post'>
		
		<table style='width: 100%' cellspacing='0'>
			<tr>
				<td class='".$this->row1."' style='padding: 5px'><b>Category Name</b><br />The title of the category.</td>
				<td class='".$this->row2."' style='padding: 5px'><input class='forminput' type='text' name='category_name'/></td>
			</tr>
			<tr>
				<td class='".$this->row1."' style='padding: 5px'><b>Category Description</b><br />A brief description of the category.</td>
				<td class='".$this->row2."' style='padding: 5px'><input class='forminput' type='text' name='category_desc'/></td>
			</tr>
			<tr>
			  <td class='".$this->row1."' style='padding: 5px'><b>Parent Category</b><br />Select an existing category to make this a subcategory.</td>
			  <td class='".$this->row2."' style='padding: 5px'>{$parent_menu}</td>
			<tr>
				<td colspan='2' class='".$this->tfoot."' style='text-align: center;'><input type='submit' value='Submit' class='realdarkbutton' /></td>
			</tr>
		</table>
		
		</form>
		" );
	}
	
	function op_do_new_cat()
	{
    	$this->ipsclass->DB->do_insert( 'ineo_categories' , array( 'category_name' => $this->ipsclass->input['category_name'], 'category_desc' => $this->ipsclass->input['category_desc'], 'category_parent' => $this->ipsclass->input['category_parent'] ) );
    	$this->ineo->libs['categories']->rebuild_cat_cache();
		$this->ipsclass->boink_it( $this->ipsclass->base_url . '&section=components&act=ineo&code=categories' );
	}
	
	function op_do_cat_edit()
	{
		$this->ipsclass->DB->do_update( 'ineo_categories' , array( 'category_name' => $this->ipsclass->input['category_name'] , 'category_desc' => $this->ipsclass->input['category_desc'], 'category_parent' => $this->ipsclass->input['category_parent'] ) , 'category_id = \'' . intval($this->ipsclass->input['cat_id']) . '\'' );
		$this->ineo->libs['categories']->rebuild_cat_cache();
		$this->ipsclass->boink_it( $this->ipsclass->base_url . '&section=components&act=ineo&code=categories' );
	}
	
	function op_tools()
	{		
		$this->ipsclass->admin->page_title = 'Tools';
		$this->ipsclass->admin->page_detail = 'This page allows you to run certain management functions for Ineo, such as recounting article numbers on categories and recounting revisions made to articles.';
		
		if( !empty( $this->ipsclass->input['msg'] ) )
		{
			$this->box( 'System Message' , "<div style='padding: 5px'>{$this->ipsclass->input['msg']}</div>" );
			$this->ipsclass->html .= '<br />';
		}
		
		$this->tool_group( 
					'Topic Converter' , 
					$this->tool_entry( 'Convert Topic'  , 'Enter a topic ID or URL to create an article from it.' , "<form action='{$this->ipsclass->base_url}&section=components&act=ineo&code=convert' method='post'>
<input type='text' style='width: 45%' name='topic' />".$this->build_dropdown(1,true)."<br /><input type='submit' value='Convert Topic' />
					</form>")
				  );
	}
	
	function tool_group( $title , $tools )
	{
		$group_html = "
		<table style='width: 100%' cellspacing='0'>
			{$tools}
		</table>
		";
		
		$this->box( $title , $group_html );
	}
	
	function tool_entry( $title , $desc , $code )
	{
		$tool = "
			<tr>
				<td class='".$this->row1."' style='padding: 5px'>
					<b>{$title}</b><br />
					{$desc}
				</td>
				<td class='".$this->row2."' style='padding: 5px; text-align: center;'>
					{$code}
				</td>
			</tr>
			";
		
		return $tool;
	}
	
	function op_convert()
	{
		$topic = $this->ipsclass->input['topic'];
		$id = intval( $topic );
		
		if( $id == 0 )
		{
			// They entered a url:
			$id = intval( preg_replace('/(.*)showtopic=([0-9]+)(.*)?/','$2',$topic) );
		}
		
		if( $id == 0 )
		{
			$this->ipsclass->boink_it($this->ipsclass->base_url . '&section=components&act=ineo&code=tools&msg=Tool Failed: No Topic ID Found');
		}
		
		$this->ipsclass->DB->simple_construct( array(
													'select' => 't.*,p.*',
													'from'   => array('topics' => 't'),
													'add_join' => array( 1 => array( 
																				
																				'type'  => 'left',
																				'from'  => array( 'posts' => 'p' ),
																				'where' => 'p.pid = t.topic_firstpost',
																		
																		)),
													'where' => 't.tid = ' . $id,
												) );
		$this->ipsclass->DB->simple_exec();
		
		$topic = $this->ipsclass->DB->fetch_row();
		
		$article = array(
							'article_title' => $topic['title'],
							'article_description' => $topic['description'],
							'article_content' => 0,
							'article_author' => $topic['starter_id'],
							'article_edited_by' => $topic['starter_id'],
							'article_created_date' => $topic['start_date'],
							'article_edited_date' => $topic['start_date'],
							'article_views' => $topic['views'],
							'article_revisions' => 1,
							'article_cat_id' => intval($this->ipsclass->input['category_parent']),
						);
		$this->ipsclass->DB->do_insert('ineo_articles',$article);
		
		$id = $this->ipsclass->DB->get_insert_id();
		
		$content = array( 'content_article' => $id , 'content_author' => $topic['starter_id'] , 'content_date' => $topic['start_date'] , 'content_content' => $topic['post'] );
		
		$this->ipsclass->DB->do_insert('ineo_content',$content);
		
		$content = $this->ipsclass->DB->get_insert_id();
		
		$this->ipsclass->DB->do_update('ineo_articles', array('article_content' => $content) , 'article_id = ' . $id );
		
		$this->ipsclass->DB->simple_construct( array('select' => 'attach_ext,attach_file,attach_location,attach_member_id,attach_filesize,attach_is_image', 'from' => 'attachments' , 'where' => 'attach_pid = ' . $topic['topic_firstpost']));
		$result = $this->ipsclass->DB->simple_exec();

		
		while( $res = $this->ipsclass->DB->fetch_row($result) )
		{
			$res['attach_article'] = $id;
			$res['attach_mid'] = $res['attach_member_id'];
			unset($res['attach_member_id']);
			$res['attach_size'] = $res['attach_filesize'];
			unset($res['attach_filesize']);
			$res['attach_isimage'] = $res['attach_is_image'];
			unset($res['attach_is_image']);
			
			$res['attach_location'] = $this->ipsclass->vars['upload_dir'] .'/'. $res['attach_location'];
			
			$this->ipsclass->DB->do_insert('ineo_attachments',$res);
		}
		
		$this->ipsclass->boink_it($this->ipsclass->base_url . '&section=components&act=ineo&code=tools&msg=Tool Completed: Article has been created!');
	}
	
	
	// Builds the dropdown for category listing.
	function build_dropdown($cid='', $no_root = false)
	{
	  $this->ipsclass->DB->simple_construct( array(
	                   'select' => 'category_id, category_name, category_parent',
	                   'from' => 'ineo_categories' ) );
    $this->ipsclass->DB->simple_exec();
    
    $this->depth_guide = '--';
	

    while( $row = $this->ipsclass->DB->fetch_row() )
    {
      $array[$row['category_parent']][$row['category_id']] = $row;
    }
    
    //echo "<pre>";print_r($array);die();
    
    $menu = '<select name="category_parent">';
	
	if( !$no_root )
	{
		$sel = ($this->ipsclass->input['parent'] == 0) ? ' selected="selected"' : '';

		$menu .= "<option value='0'{$sel}>Root Category</option>";
	}
	
    $menu .= $this->build_jump_internal( '0', $array, $cid );
    $menu .= '</select>';
    
    return $menu;
	}
	
	// Recursivityityity!!
  function build_jump_internal($root_id, $array, $selected_id, $jump_string="", $depth_guide="" )
  {
	
    if ( is_array( $array[ $root_id ] ) )
    {
      foreach( $array[ $root_id ] as $id => $cat_data )
      {
      $selected = "";
      if ( $selected_id == $cat_data['category_id'] )
      {
        $selected = ' selected="selected"';
      }
      
      $prefix = $depth_guide == '' ? '' : '&nbsp;&nbsp;&#0124;' ;
      
      $jump_string .= "<option value=\"{$cat_data['category_id']}\"".$selected.">".$prefix.$depth_guide." ".$cat_data['category_name']."</option>\n";
      $jump_string = $this->build_jump_internal( $cat_data['category_id'], $array, $selected_id, $jump_string, $depth_guide . $this->depth_guide );
      }
    }
	  return $jump_string;
  }

}

?>
